package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.customercommunicate.pojo.dto.CustomerDynamicAddDTO;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.WorkOrderErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.message.constant.WorkOrderPushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.service.MessageService;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.pro.workorder.pojo.CreateNodeReturnPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowUserEntity;
import com.xbongbong.saas.domain.entity.WorkOrderProductEntity;
import com.xbongbong.saas.domain.entity.WorkOrderStageEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.WorkOrderStatusEnum;
import com.xbongbong.saas.enums.WorkOrderTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.help.workflow.WorkOrderHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.WorkOrderFlowNodeModel;
import com.xbongbong.saas.model.WorkOrderFlowUserModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkOrderProductModel;
import com.xbongbong.saas.model.WorkOrderStageModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowWorkOrderStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;
    @Resource
    private WorkOrderStageModel workOrderStageModel;
    @Resource
    private WorkOrderFlowNodeModel workOrderFlowNodeModel;
    @Resource
    private UserModel userModel;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private WorkOrderHelp workOrderHelp;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private WorkOrderFlowUserModel workOrderFlowUserModel;
    @Resource
    private WorkOrderProductModel workOrderProductModel;
    @Resource
    private MessageService messageService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private CustomerCommunicateService customerCommunicateService;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.WORK_ORDER.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        Long dataId = pojoData.getId();
        JSONObject data = pojoData.getData();
        User user = workflowTransferPOJO.getUser();
        String creatorId = user.getUserId();

        WorkOrderEntity workOrderEntity = workOrderModel.getByKey(dataId, corpid);
        Long templateId = workOrderEntity.getTemplateId();

        //获取工单的模板，根据模板产生相应的工单流程
        WorkOrderTemplateEntity templateEntity = workOrderTemplateModel.getBykey(templateId, corpid);
        if (templateEntity == null) {
            throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222011);
        }
        Integer expectedTime = 0;
        WorkOrderStageEntity workOrderStageEntity = null;
        //当前阶段id
        Long nowStageId = 0L;
        //阶段名称
        String stageName = "";
        boolean ifFree = Objects.equals(templateEntity.getIsFree(), 1);
        //产生相应的工单流程, 自由流程和指定流程的预计时间不同计算
        if (ifFree) {
            //自由流程
            expectedTime = templateEntity.getExpectedTime();
        } else {
            //指定流程
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("templateId", templateEntity.getId());
            param.put("corpid", corpid);
            param.put("del", 0);
            param.put("orderByStr", "sort");
            List<WorkOrderStageEntity> stageEntityList = workOrderStageModel.findEntitys(param);
            if (stageEntityList.isEmpty()) {
                throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222025);
            }
            //取第一个阶段
            workOrderStageEntity = stageEntityList.get(0);
            nowStageId = workOrderStageEntity.getId();
            for (WorkOrderStageEntity entity : stageEntityList) {
                expectedTime += entity.getExpectedTime();
            }
            stageName = workOrderStageEntity.getName();
        }
        //存入阶段名称(阶段名称为空时不存)
        if (!Objects.equals(stageName, "")) {
            data.put(WorkOrderEnum.STAGE_NAME.getAttr(), stageName);
        }
        templateEntity.setExpectedTime(expectedTime);
        workOrderEntity.setStatus(WorkOrderStatusEnum.UNACCEPTED.getCode());
        workOrderEntity.setNowStageId(nowStageId);
        workOrderEntity.setExpectedTime(expectedTime);
        workOrderEntity.setActualTime(0);
        workOrderEntity.setStartTime(0L);
        workOrderEntity.setEndTime(0L);
        workOrderEntity.setCloseTime(0L);

        //获取工单流程设置, 新建第一个节点, 生成工单流程节点
        CreateNodeReturnPojo createNodeReturnPojo = workOrderHelp.createNode(workOrderEntity,templateEntity,workOrderStageEntity);
        if (createNodeReturnPojo.getIsRob()) {
            workOrderEntity.setType(WorkOrderTypeEnum.ROB.getCode());
        }
        Integer nodeStatus = createNodeReturnPojo.getWorkOrderFlowNodeEntity().getStatus();
        data.put(WorkOrderEnum.NODE_STATUS.getAttr(), nodeStatus);

        formatSelectProduct4Save2(data, WorkOrderEnum.SPARE_PARTS.getAttr());
        FormDataUtil.removeSystemData(data);
        workOrderEntity.setData(data);
        workOrderModel.save(workOrderEntity);
        data.put(BasicConstant.SERIAL_NO, workOrderEntity.getSerialNo());
        workOrderFlowNodeModel.save(createNodeReturnPojo.getWorkOrderFlowNodeEntity());
        //新建节点的用户id
        String userId = createNodeReturnPojo.getUserId();
        workOrderHelp.createNewMain(dataId, corpid, userId);

        //生成抄送人员数据
        workOrderHelp.saveCC(dataId, corpid, JSONArray.parseArray(templateEntity.getCc()));

        UserEntity creator = userModel.getByKeyIngoreDel(creatorId, corpid);
        //消息推送
        if (userId == null ) {
            //抢单推送
            PushRefTypePojo.Options options = new PushRefTypePojo.Options(workOrderEntity.getAppId(), workOrderEntity.getMenuId(), workOrderEntity.getFormId(), workOrderEntity.getId(), SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode());
            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, new ArrayList<>(createNodeReturnPojo.getPushIdList()), Collections.singletonList(dataId), 0, DateTimeUtil.getInt(), I18nMessageUtil.getMessage(WorkOrderPushConstant.WORK_ORDER_WAIT_ROB_TITLE), String.format(I18nMessageUtil.getMessage(WorkOrderPushConstant.PUSH_TO_ROB), workOrderEntity.getSerialNo(), workOrderStageEntity.getName()), null, options);
            messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.WORKORDER_PUSH);

        } else {
            List<String> pushUserIds;
            String pushMsg;
            UserEntity userEntity = userModel.getByKey(userId, corpid);
            if (Objects.equals(creatorId, userId)) {
                //创建人为第一阶段负责人
                pushUserIds = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.WORKORDER_NEW_EXECUTED.getCode(), PushTypeEnum.WORKORDER_NEW_EXECUTED.getSubCode(), userEntity, workOrderEntity);

                JSONObject dataObj = workOrderEntity.getData();
                String implementingTimeStr = "";
                if (Objects.nonNull(dataObj)) {
                    Long time = dataObj.getLong(WorkOrderEnum.IMPLEMENTATION_TIME.getAttr());
                    if (Objects.nonNull(time)) {
                        implementingTimeStr = DateTimeUtil.getString(time * 1000, DateTimeUtil.SDFYMDHM);
                    }
                }
                if (implementingTimeStr.isEmpty()) {
                    pushMsg = String.format(I18nMessageUtil.getMessage(WorkOrderPushConstant.PUSH_NEW_NO_TIME), userEntity.getName(), workOrderEntity.getSerialNo());
                } else {
                    pushMsg = String.format(I18nMessageUtil.getMessage(WorkOrderPushConstant.PUSH_NEW), userEntity.getName(), workOrderEntity.getSerialNo(), implementingTimeStr);
                }
                PushRefTypePojo.Options options = new PushRefTypePojo.Options(workOrderEntity.getAppId(), workOrderEntity.getMenuId(), workOrderEntity.getFormId(), workOrderEntity.getId(), SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode());

                MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserIds, Collections.singletonList(dataId), 0, DateTimeUtil.getInt(), I18nMessageUtil.getMessage(WorkOrderPushConstant.WORKORDER_NEW_EXECUTED_TITLE), pushMsg, null, options);
                messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.WORKORDER_NEW_EXECUTED);

            } else {
                //创建人不为第一阶段负责人
                // UserEntity creator = userModel.getByKey(creatorId, corpid);
                if (Objects.nonNull(creator)) {
//                if (!Objects.equals(saasFormSaveDTO.getFromOuterLink(),1)){
                    if (Objects.equals(userId, creatorId)) {
                        //操作人和指定的人相同
                        pushMsg = String.format(I18nMessageUtil.getMessage(WorkOrderPushConstant.PUSH_NEW_TODO), creator.getName(), workOrderEntity.getSerialNo());
                        pushUserIds = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.WORKORDER_NEW_EXECUTOR.getCode(), PushTypeEnum.WORKORDER_NEW_EXECUTOR.getSubCode(), userEntity, workOrderEntity);
                        PushRefTypePojo.Options options = new PushRefTypePojo.Options(workOrderEntity.getAppId(), workOrderEntity.getMenuId(), workOrderEntity.getFormId(), workOrderEntity.getId(), SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode());

                        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserIds, Collections.singletonList(dataId), 0, DateTimeUtil.getInt(), I18nMessageUtil.getMessage(WorkOrderPushConstant.WORKORDER_NEW_EXECUTOR_TITLE), pushMsg, null, options);
                        messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.WORKORDER_NEW_EXECUTOR);
                    } else {
                        //操作人和指定的人不同
                        pushMsg = String.format(I18nMessageUtil.getMessage(WorkOrderPushConstant.PUSH_NEW_TODO), creator.getName(), workOrderEntity.getSerialNo());
                        pushUserIds = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.WORKORDER_NEW_EXECUTOR.getCode(), PushTypeEnum.WORKORDER_NEW_EXECUTOR.getSubCode(), creator, workOrderEntity);
                        PushRefTypePojo.Options options = new PushRefTypePojo.Options(workOrderEntity.getAppId(), workOrderEntity.getMenuId(), workOrderEntity.getFormId(), workOrderEntity.getId(), SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode());

                        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserIds, Collections.singletonList(dataId), 0, DateTimeUtil.getInt(), I18nMessageUtil.getMessage(WorkOrderPushConstant.WORKORDER_NEW_EXECUTOR_TITLE), pushMsg, null, options);
                        messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.WORKORDER_NEW_EXECUTOR);
                    }
//                }
                }


            }

        }

        try {
            if(isNotDistributeBusinessType(workflowTransferPOJO)) {
                String memo;
                String communicateMemo;
                if (Objects.equals(workflowTransferPOJO.getIsImport(), BasicConstant.ONE)) {
                    memo = CrmLogMemoConstant.DYNAMIC_USER_IMPORT;
                } else {
                    memo = CrmLogMemoConstant.DYNAMIC_USER_ADD;
                }
                PaasFormEntity paasForm = proFormHelp.getPaasForm(pojoData.getFormId(), pojoData.getBusinessType(), corpid);
                String paasFormName = XbbRefTypeEnum.WORK_ORDER.getName();
                if (Objects.nonNull(paasForm)) {
                    paasFormName = paasForm.getName();
                }
                String serialNo = workOrderEntity.getSerialNo();
                String creatorName = Objects.nonNull(creator) ? creator.getName() : "";
                communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorName, paasFormName, serialNo);

                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(creatorId);
                customerDynamicAddDTO.setCustomerId(data.getLong(WorkOrderEnum.LINK_CUSTOMER.getAttr()));
                customerDynamicAddDTO.setOpportunityIds(FastJsonHelper.getTransferTypesFromData(data, WorkOrderEnum.LINK_OPPORTUNITY.getAttr(), Long.class));
                customerDynamicAddDTO.setContractIds(FastJsonHelper.getTransferTypesFromData(data, WorkOrderEnum.LINK_CONTRACT.getAttr(), Long.class));
                customerDynamicAddDTO.setContactIds(FastJsonHelper.getTransferTypesFromData(data, WorkOrderEnum.LINK_CONTACT.getAttr(), Long.class));
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setCommunicateBusinessText(serialNo);
                customerDynamicAddDTO.setCommunicateBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
                customerDynamicAddDTO.setDataId(dataId);
                customerDynamicAddDTO.setLogType(ProjectLogEnum.WORK_ORDER_CREATE.getSubType());
                customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowWorkOrderStrategy.save", e);
        }

        // api
        apiHook(workflowTransferPOJO);
        addLinkDataDynamic(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);



        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        String corpid = workflowTransferPOJO.getCorpid();
        Long backupDataId = workflowTransferPOJO.getBackupDataId();
        Long dataId = workflowTransferPOJO.getData().getId();
        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
        if (Objects.nonNull(workflowBackupDataEntity)) {
            JSONObject data = workflowBackupDataEntity.getData();

            replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

            WorkOrderEntity workOrderEntity = new WorkOrderEntity();
            workOrderEntity.setId(dataId);
            workOrderEntity.setCorpid(workflowTransferPOJO.getCorpid());
            workOrderEntity.setData(data);
            workOrderEntity.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));

            workOrderEntity.setOwnerId(getOwnerId(data));
            workOrderEntity.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
            List<WorkOrderProductEntity> workOrderProductEntities = JSON.parseArray(data.getString(StringConstant.PRODUCT), WorkOrderProductEntity.class);
            List<WorkOrderFlowUserEntity> workOrderFlowUserEntities = JSON.parseArray(data.getString(StringConstant.USER_TEAM), WorkOrderFlowUserEntity.class);

            FormDataUtil.removeSystemData(data);
            data.remove(StringConstant.PRODUCT);
            data.remove(StringConstant.USER_TEAM);
            if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                workOrderEntity.setFlowStatus(FlowStatusEnum.PASS.getType());
            }
            workOrderModel.update(workOrderEntity);
            // 回退被删掉的子表单
            updateBackSubForm(workOrderEntity, corpid, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);
            //回退被删掉的富文本
            updateBackRichText(taskId, workflowTransferPOJO);
            // 团队保存
            saveUserTeam(workOrderFlowUserEntities, corpid, workOrderEntity.getId());
            // 产品保存
            saveProduct(workOrderProductEntities, corpid, workOrderEntity.getId());

        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            WorkOrderEntity workOrderEntity = new WorkOrderEntity();
            workOrderEntity.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                workOrderEntity.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                workOrderEntity.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            workOrderEntity.setCorpid(corpid);
            workOrderEntity.setUpdateTime(DateTimeUtil.getInt());
            workOrderModel.update(workOrderEntity);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            // 产品
            List<WorkOrderProductEntity> products = workOrderProductModel.getProductsByWorkOrderId(dataId, corpid);
            if (CollectionUtils.isNotEmpty(products)) {
                List<Long> deleteList = new ArrayList<>();
                products.forEach(item->{
                    deleteList.add(item.getId());
                });
                workOrderProductModel.deleteBatch(deleteList, corpid, del.getDel());

            }
            List<WorkOrderFlowUserEntity> orderFlowUserEntities = workOrderFlowUserModel.getUserListByWorkorderId(corpid, dataId);
            if (CollectionUtils.isNotEmpty(orderFlowUserEntities)) {
                workOrderFlowUserModel.deleteBatch(orderFlowUserEntities, corpid, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowWorkOrderStrategy.approvalFailed error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveProduct(List<WorkOrderProductEntity> workOrderProductEntities, String corpid, Long id) throws XbbException {
        try {
            if (CollectionUtils.isEmpty(workOrderProductEntities)) {
                return;
            }

            List<WorkOrderProductEntity> products = workOrderProductModel.getProductsByWorkOrderId(id, corpid);

            List<Long> ids = new ArrayList<>();
            workOrderProductEntities.forEach(v -> ids.add(v.getId()));

            List<Long> deleteIds = products.stream().filter(v -> !ids.contains(v.getId())).map(WorkOrderProductEntity::getId).collect(Collectors.toList());

            workOrderProductModel.deleteBatch(deleteIds, corpid, DelEnum.DELETE.getDel());

            workOrderProductModel.updateMulti(workOrderProductEntities, corpid);

        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowWorkOrderStrategy.saveProduct error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveUserTeam(List<WorkOrderFlowUserEntity> workOrderFlowUserEntities, String corpid, Long id) throws XbbException {
        try {
            List<WorkOrderFlowUserEntity> orderFlowUserEntities = workOrderFlowUserModel.getUserListByWorkorderId(corpid, id);
            Set<Long> idList = new HashSet<>();
            workOrderFlowUserEntities.forEach(v -> idList.add(v.getId()));

            List<WorkOrderFlowUserEntity> userEntities = orderFlowUserEntities.stream().filter(v -> !idList.contains(v.getId())).collect(Collectors.toList());

            workOrderFlowUserModel.deleteBatch(userEntities, corpid, DelEnum.DELETE.getDel());

            workOrderFlowUserModel.updateBatch(workOrderFlowUserEntities, corpid);

        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowWorkOrderStrategy.saveUserTeam error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    public JSONArray formatSelectProduct4Save2(JSONObject data, String attr) throws XbbException {
        if (data == null || attr == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
        }
        try {
            JSONArray productArray = data.getJSONArray(attr);
            if (productArray == null) {
                return new JSONArray();
            }
            Set<Long> ids = new HashSet<>();
            for (int i = 0; i < productArray.size(); i++) {
                JSONObject jsonObject = productArray.getJSONObject(i);
                if (jsonObject != null) {
                    Long productId = jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr());
                    ids.add(productId);
                }
            }
            data.put(attr, ids.toArray());
            return productArray;
        } catch (Exception e) {
            data.put(attr, new JSONArray());
            return new JSONArray();
        }
    }
}
